package com.springboot.util.uuid;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author zyj
 * @description
 * @date 2018/7/24 9:56
 **/
@Component
@Slf4j
public class DbUtilUuid {

    private long workerId = 0;
    private long datacenterId = 1;
    private Snowflake snowFlake = IdUtil.createSnowflake(workerId, datacenterId);

    @PostConstruct
    public void init() {
        try {
            // 将网络ip转换成long
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        } catch (Exception e) {
            log.error("DbUtilUuid init:", e);
        }
    }

    /**
     * 获取雪花ID
     * @return
     */
    public synchronized Long getDatabaseId() {
        return this.snowFlake.nextId();
    }

    public synchronized long getDatabaseId(long workerId, long datacenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }

    public static void main(String[] args) {
        DbUtilUuid snowFlakeDemo = new DbUtilUuid();
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                System.out.println(snowFlakeDemo.getDatabaseId());
            }, String.valueOf(i)).start();
        }
    }


}
